<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;

use think\Request;

use cmf\controller\AdminBaseController;
use app\admin\model\GPSCategory;
use app\admin\model\GPSCategoryItem;
use app\admin\model\GPSMigration;

class GPSCategoryController extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $category = Db::table('gps_category')
            ->order("id desc")
            ->paginate(100);

        // 获取分页显示
        $page = $category->render();

        $this->assign("category", $category);
        $this->assign("page", $page);

        return $this->fetch('GPSCategory/index');
    }

    /**
     * 添加gps分类 
     * Author Raven
     * Date 2018-10-07
     */
    public function add(Request $request)
    {
        $category_name = trim($request->post('category_name'));

        if(empty($category_name)){
            $this->error("请输入分类名称");
        }

        $Dao = new GPSCategory();

        $has = $Dao->hasCagegoryName($category_name);

        if($has){
            $this->error('分类信息已存在');
        }

        try {
            $Dao->category_name = $category_name;
            $Dao->hex_name = randomChar(8);
            $add = $Dao->save();
        } catch (Exception $e) {
            $add = false;
        }
        

        if($add){
            $this->success("分类添加成功", url('GPSCategory/index'));
        }else{
            $this->error('分类添加失败');
        }
    }

    /**
     * 编辑gps分类 
     * Author Raven
     * Date 2018-10-07
     */
    public function edit(Request $request)
    {
        $category_id = intval($request->post('category_id'));
        $category_name = trim($request->post('category_name'));

        if(empty($category_id)){
            $this->error("缺少必要的参数");
        }

        if(empty($category_name)){
            $this->error("请输入分类名称");
        }

        $Dao = GPSCategory::where('id', $category_id)
            ->find();

        if(empty($Dao)){
            $this->error("分类信息查询失败");
        }

        try {
            $Dao->category_name = $category_name;
            $save = $Dao->save();
        } catch (Exception $e) {
            $save = false;
        }
        

        if($save){
            $this->success("分类编辑成功", url('GPSCategory/index'));
        }else{
            $this->error('分类编辑失败');
        }
    }

    /**
     * 展示添加列表项 
     * Author Raven
     * Date 2018-10-07
     */
    public function showItem(Request $request)
    {
        $category_id = intval($request->get('id'));

        $categoryInfo = GPSCategory::where('id', $category_id)
            ->field(['id', 'category_name', 'hex_name', 'status'])
            ->find();

        $categoryItem = GPSCategoryItem::where('fk_category_id', $category_id)
            ->field((['id', 'item_name', 'item_type', 'item_hex', 'status']))
            ->order('item_order', 'asc')
            ->select();

        if(empty($categoryInfo)){
            echo "<h1>分类信息查询失败</h1>";
            exit;
        }

        $this->assign('category', $categoryInfo);
        $this->assign('item', $categoryItem);

        return $this->fetch('GPSCategory/show_item');
    }

    /**
     * 创建表单项 
     * Author Raven
     * Date 2018-10-07
     */
    public function create_item(Request $request)
    {
        $category_id = intval($request->post('category_id'));
        $itemIndex = $_POST['item_index'];
        $item = $request->post();

        if(empty($itemIndex)){
            $this->error("请输入分类字段");
        }
        Db::startTrans();
        $GPSCategory = new GPSCategory();
        $GPSCategoryItem = new GPSCategoryItem();
        
        $GPSCategoryItem->removeItemByCatId($category_id);

        $data = $GPSCategoryItem->createDataByItemIndex($category_id, $itemIndex, $item);

        $updateStatus = $GPSCategory
            ->updateStatusByCategoryId($category_id, GPSCategory::STATUS_NO_UPDATE_TABLE);

        if($updateStatus === false){
            $this->error("采集字段增加失败");
            Db::rollback();
        }

        $res = true;
        try {
            $add = $GPSCategoryItem->saveAll($data);
            Db::commit();
        } catch (\Exception $e) {
            $res = false;
        }

        if($res){
            $this->success("采集字段添加成功");
        }else{
            $this->error("采集字段增加失败");
            Db::rollback();
        }
    }

    /**
     * 更新字段显示状态 
     * Author Raven
     * Date 2018-10-07
     */
    public function update_item_status(Request $request)
    {
        $item_id = intval($request->post('item_id'));
        $item_status = intval($request->post('item_status'));

        $Dao = GPSCategoryItem::where('id', $item_id)
            ->find();

        if(empty($Dao)){
            $this->error("字段信息查询失败");
        }

        $Dao->status = $item_status;
        $save = $Dao->save();

        if($save){
            $this->success('success');
        }else{
            $this->error('字段信息更新失败');
        }
    }

    /**
     * 创建数据表 
     * Author Raven
     * Date 2018-10-07
     */
    public function create_table(Request $request)
    {
        $category_id = intval($request->get('category_id'));

        $categoryInfo = GPSCategory::where('id', $category_id)
            ->field(['hex_name', 'status'])
            ->find();

        if(empty($categoryInfo)){
            $this->error("分类信息查询失败");
        }

        if($categoryInfo->status != GPSCategory::STATUS_NO_UPDATE_TABLE){
            $this->error("分类状态异常");
        }

        $GPSCategory = new GPSCategory();
        $GPSCategoryItem = new GPSCategoryItem();

        $item = $GPSCategoryItem->getItemHexByCatId($category_id);

        if(count($item) < 1){
            $this->error('该分类下没有添加字段');
        }

        $GPSMigration = new GPSMigration();

        $create = $GPSMigration->createTable($categoryInfo->hex_name, $item);

        if($create == false){
            $this->error('数据表创建失败');
        }

        $GPSCategory
            ->updateStatusByCategoryId($category_id, GPSCategory::STATUS_UPDATE_TABLE_SUCCESS);

        $this->success('success');
    }

    /**
     * 显示建表语句 
     * Author Raven
     * Date 2018-10-07
     */
    public function show_create_table(Request $request)
    {
        $category_id = intval($request->get('category_id'));

        $categoryInfo = GPSCategory::where('id', $category_id)
            ->field(['hex_name'])
            ->find();

        if(empty($categoryInfo)){
            $this->error("分类信息查询失败");
        }

        $GPSCategory = new GPSCategory();
        $GPSCategoryItem = new GPSCategoryItem();

        $itemCnt = $GPSCategoryItem->getItemCountByCatId($category_id);

        if($itemCnt < 1){
            $this->error('该分类下没有添加字段');
        }

        $GPSMigration = new GPSMigration();

        $tab_name = sprintf(GPSMigration::TABLE_PREFIX, $categoryInfo->hex_name);
        $sql = $GPSMigration->showTable($tab_name);

        $res = [
            'sql' => $sql
        ];
        $this->success("success", '', $res);
    }

    /**
     * 获取字段类型 
     * Author Raven
     * Date 2018-10-09
     */
    public function get_item_type(Request $request)
    {
        $item_id = intval($request->get('item_id'));

        if(empty($item_id)){
            $this->error('缺少必要的参数');
        }

        $GPSCategoryItem = new GPSCategoryItem();

        $itemInfo = $GPSCategoryItem
            ->where('id', $item_id)
            ->field(['id', 'item_type', 'item_value'])
            ->find();

        if(empty($itemInfo)){
            $this->error('字段信息不存在');
        }

        $this->success('success', '', $itemInfo);
    }

    /**
     * 保存字段类型 
     * Author Raven
     * Date 2018-10-09
     */
    public function save_item_type(Request $request)
    {
        $item_id = intval($request->post('item_id'));
        $item_type = intval($request->post('item_type'));
        $item_value = trim($request->post('item_value'));
        $item_value_arr = explode("|", $item_value);


        if(empty($item_id) || empty($item_type)){
            $this->error('缺少必要的参数');
        }

        if($item_type != '1' && empty($item_value_arr[0])){
            $this->error('请输入字段值');
        }
        $GPSCategoryItem = new GPSCategoryItem();

        $Dao = $GPSCategoryItem
            ->where('id', $item_id)
            ->find();

        if(empty($Dao)){
            $this->error('字段信息不存在');
        }

        try {
            $Dao->item_type = $item_type;
            $Dao->item_value = $item_value;

            $res = $Dao->save();
        } catch (Exception $e) {
            $res = false;
        }

        if($res){
            $this->success('success');
        }else{
            $this->error('数据保存失败');
        }

    }
}
